/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */

package BeanView;

import Dao.DaoAddress;
import Dao.DaoOrganization;
import HibernateUtil.HibernateUtil;
import Pojo.Address;
import Pojo.Employees;
import Pojo.Organization;
import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import javax.faces.application.FacesMessage;
import javax.faces.bean.ManagedBean;
import javax.faces.bean.ViewScoped;
import javax.faces.context.FacesContext;
import org.hibernate.Session;
import org.hibernate.Transaction;
import org.primefaces.context.RequestContext;
import org.primefaces.event.SelectEvent;

/**
 *
 * @author olegk
 */
@ManagedBean
@ViewScoped
public class MbVOrganization implements java.io.Serializable{
    private Session session;
    private Transaction transaction;
    private Organization organization;
    private Organization newOrganization;
    private List<Organization> listOrganization;
    private Address address;

    public MbVOrganization(){
        this.newOrganization=new Organization();
        this.newOrganization.setId(0L);
        this.organization=new Organization();
        this.organization.setId(0L);
        
        this.address = new Address();
    }
    
    public void registration()
    {
        this.session=null;
        this.transaction=null;        
        try
        {            
            DaoOrganization daoOrganization=new DaoOrganization();
            this.session=HibernateUtil.getSessionFactory().openSession();
            this.transaction=session.beginTransaction();
            String query = "from Organization o where o.inn = ?";
            List<Object> param = Arrays.asList((Object)this.newOrganization.getInn());
            if(daoOrganization.selectOrganizationName(this.session, query, param)!=null)
            {
                FacesContext.getCurrentInstance().addMessage(null, new FacesMessage(FacesMessage.SEVERITY_ERROR, "Ошибка:", "Организация уже зарегистрирована в системе"));
                return;
            }          
            
            DaoAddress daoAddress=new DaoAddress();
            daoAddress.register(this.session, this.address);
            this.newOrganization.setAddressId(this.address.getId());
            
            daoOrganization.register(this.session, this.newOrganization);            
            this.transaction.commit();            
            FacesContext.getCurrentInstance().addMessage(null, new FacesMessage(FacesMessage.SEVERITY_INFO, "Успех:", "Регистрация прошла успешно"));
            this.organization=new Organization();
            this.organization.setId(0L);
            
            RequestContext.getCurrentInstance().execute("PF('dialogNewOrganization').hide()");
        }
        catch(Exception ex)
        {
            if(this.transaction!=null)
            {
                this.transaction.rollback();
            }            
            FacesContext.getCurrentInstance().addMessage(null, new FacesMessage(FacesMessage.SEVERITY_FATAL, "Фатальная ошибка:", "Пожалуйста, обратитесь к администратору "+ex.getMessage()));
        }
        finally
        {
            if(this.session!=null)
            {
                this.session.close();
            }
        }
    }

    public void remove(){
        this.session=null;
        this.transaction=null;        
        try
        {            
            DaoOrganization daoOrganization=new DaoOrganization();
            this.session=HibernateUtil.getSessionFactory().openSession();
            this.transaction=session.beginTransaction();                     
            daoOrganization.delete(this.session, this.organization);            
            this.transaction.commit();            
            FacesContext.getCurrentInstance().addMessage(null, new FacesMessage(FacesMessage.SEVERITY_INFO, "Успех:", "Организация удалена"));
            this.organization=new Organization();
            this.organization.setId(0L);
        }
        catch(Exception ex)
        {
            if(this.transaction!=null)
            {
                this.transaction.rollback();
            }            
            FacesContext.getCurrentInstance().addMessage(null, new FacesMessage(FacesMessage.SEVERITY_FATAL, "Фатальная ошибка:", "Пожалуйста, обратитесь к администратору "+ex.getMessage()));
        }
        finally
        {
            if(this.session!=null)
            {
                this.session.close();
            }
        }
    }
    
    public List<Organization> getAll()
    {
        this.session=null;
        this.transaction=null;        
        try
        {
            DaoOrganization daoOrganization=new DaoOrganization();            
            this.session=HibernateUtil.getSessionFactory().openSession();
            this.transaction=this.session.beginTransaction();            
            this.listOrganization=daoOrganization.getAll(this.session);            
            this.transaction.commit();            
            return this.listOrganization;
        }
        catch(Exception ex)
        {
            if(this.transaction!=null)
            {
                this.transaction.rollback();
            }            
            FacesContext.getCurrentInstance().addMessage(null, new FacesMessage(FacesMessage.SEVERITY_FATAL, "Фатальная ошибка:", "Пожалуйста, обратитесь к администратору "+ex.getMessage()));            
            return null;
        }
        finally
        {
            if(this.session!=null)
            {
                this.session.close();
            }
        }
    }
    
    public Organization getId(String id){
        this.session=null;
        this.transaction=null;        
        try
        {
            DaoOrganization daoOrganization=new DaoOrganization();            
            this.session=HibernateUtil.getSessionFactory().openSession();
            this.transaction=this.session.beginTransaction();  
            String query = "from Organization o where o.id = ?";
            List<Object> param = Arrays.asList((Object)Long.parseLong(id));
            this.organization=daoOrganization.selectOrganizationName(this.session, query, param);           
            this.transaction.commit();            
            return this.organization;
        }
        catch(Exception ex)
        {
            if(this.transaction!=null)
            {
                this.transaction.rollback();
            }            
            FacesContext.getCurrentInstance().addMessage(null, new FacesMessage(FacesMessage.SEVERITY_FATAL, "Фатальная ошибка:", "Пожалуйста, обратитесь к администратору "+ex.getMessage()));            
            return null;
        }
        finally
        {
            if(this.session!=null)
            {
                this.session.close();
            }
        }
    }
    
/*    public void editTable(Long id){
        this.session=null;
        this.transaction=null;        
        try
        {
            DaoOrganization daoOrganizaton = new DaoOrganization();            
            this.session = HibernateUtil.getSessionFactory().openSession();
            this.transaction = session.beginTransaction();            
            this.organization = daoOrganizaton.getSelectOrganization(this.session, "from Organization o where o.id = ", id);
            this.transaction.commit();
        }
        catch(Exception ex)
        {
            if(this.transaction!=null)
            {
                this.transaction.rollback();
            }            
            FacesContext.getCurrentInstance().addMessage(null, new FacesMessage(FacesMessage.SEVERITY_FATAL, "Фатальная ошибка:", "Пожалуйста, обратитесь к администратору "+ex.getMessage()));
        }
        finally
        {
            if(this.session!=null)
            {
                this.session.close();
            }
        }
    }*/
    
    public void update(){
        this.session=null;
        this.transaction=null;        
        try
        {            
            DaoOrganization daoOrganization=new DaoOrganization();
            this.session=HibernateUtil.getSessionFactory().openSession();
            this.transaction=session.beginTransaction();
            String query = "from Organization o where o.id <> ? and o.inn = ?";
            List<Object> param = Arrays.asList((Object)this.organization.getId(), 
                                this.organization.getInn());
            if(daoOrganization.selectOrganizationName(this.session, query, param)!=null)
            {
                FacesContext.getCurrentInstance().addMessage(null, new FacesMessage(FacesMessage.SEVERITY_ERROR, "Ошибка:", "Организация уже зарегистрирована в системе"));
                return;
            }           
            daoOrganization.update(this.session, this.organization);            
            this.transaction.commit();            
            FacesContext.getCurrentInstance().addMessage(null, new FacesMessage(FacesMessage.SEVERITY_INFO, "Успех:", "Регистрация прошла успешно"));
            this.organization=new Organization();
            this.organization.setId(0L);
        }
        catch(Exception ex)
        {
            if(this.transaction!=null)
            {
                this.transaction.rollback();
            }            
            FacesContext.getCurrentInstance().addMessage(null, new FacesMessage(FacesMessage.SEVERITY_FATAL, "Фатальная ошибка:", "Пожалуйста, обратитесь к администратору "+ex.getMessage()));
        }
        finally
        {
            if(this.session!=null)
            {
                this.session.close();
            }
        }
    }
    
    public String cancel(){
        this.organization=new Organization();
        this.organization.setId(0L);
        return null;
    }
    
    public void setOrganizationParent(){
        Object parent=FacesContext.getCurrentInstance().getExternalContext().getSessionMap().get("parent");
        if(parent instanceof Employees){
            Employees employees=(Employees)parent;
            employees.setOrganization(this.organization);
        } 
        this.organization=new Organization();
        this.organization.setId(0L);
    }
    
    public void setAddressOrganization(){
        // FacesContext.getCurrentInstance().getExternalContext().getSessionMap().put("parent",this.address);
        // RequestContext.getCurrentInstance().execute("PF('dialogAddress').show()");
        
        Map<String,Object> options = new HashMap<String, Object>();
        options.put("modal", true);
        options.put("draggable", false);
        options.put("resizable", false);
        options.put("contentWidth", 800);
        options.put("contentHeight", 420);
        
        RequestContext.getCurrentInstance().openDialog("/fias/address", options, null);
    }
    
    public void onAddressChosen(SelectEvent event){
        this.address = (Address) event.getObject();
    }

    public Organization getOrganization() {
        return organization;
    }

    public void setOrganization(Organization organization) {
        this.organization = organization;
    }

    public Organization getNewOrganization() {
        return newOrganization;
    }

    public void setNewOrganization(Organization newOrganization) {
        this.newOrganization = newOrganization;
    }  
    
    public Address getAddress() {
        return address;
    }

    public void setAddress(Address address) {
        this.address = address;
    }
}
